<template>
  <view class="post-detail-page">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="navbar-content">
        <view class="back-btn" @tap="goBack">
          <text class="iconfont">←</text>
        </view>
        <text class="navbar-title">帖子详情</text>
        <view class="more-btn">
          <text class="iconfont">⋯</text>
        </view>
      </view>
    </view>

    <scroll-view class="content-scroll" scroll-y :style="{ paddingTop: (statusBarHeight + 88) + 'rpx' }">
      <!-- 帖子内容 -->
      <view class="post-content">
        <!-- 标题 -->
        <view class="post-title">{{ postData.title }}</view>
        
        <!-- 用户信息 -->
        <view class="user-info" @tap="viewUserProfile(postData.userIdStr)">
          <image :src="postData.avatarUrl" mode="aspectFill" class="avatar"></image>
          <view class="user-detail">
            <text class="username">{{ postData.nickName }}</text>
            <text class="post-time">{{ postData.createTime }}</text>
          </view>
        </view>
        
        <!-- 正文 -->
        <view class="post-body">{{ postData.content }}</view>
        
        <!-- 图片九宫格 -->
        <view class="post-images" v-if="postData.imageUrls && postData.imageUrls.length > 0">
          <view class="image-grid">
            <view 
              class="grid-item" 
              v-for="(url, index) in postData.imageUrls.slice(0, 9)" 
              :key="index"
              :style="{
                width: `calc(33.33% - 12rpx)`,
                height: imageHeight(postData.imageUrls.length)
              }"
              @tap="previewImage(index)"
            >
              <image 
                :src="url" 
                mode="aspectFill" 
                class="post-image" 
              ></image>
              <!-- 超过9张显示数量提示 -->
              <view class="image-count" v-if="index === 8 && postData.imageUrls.length > 9">
                <text>+{{ postData.imageUrls.length - 9 }}</text>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 帖子操作 -->
        <view class="post-actions">
          <view class="action-item" @tap="likePost">
            <text class="iconfont" :class="{'active': isLiked}">❤</text>
            <text class="action-text">{{ postData.likeCount }}</text>
          </view>
          <view class="action-item" @tap="openMainComment">
            <text class="iconfont">💬</text>
            <text class="action-text">{{ postData.commentCount }}</text>
          </view>
          <view class="action-item" @tap="favoritePost">
            <text class="iconfont" :class="{'active': isFavorited}">★</text>
            <text class="action-text">{{ postData.favoriteCount }}</text>
          </view>
          <view class="action-item">
            <text class="iconfont">↗️</text>
            <text class="action-text">分享</text>
          </view>
        </view>
      </view>
      
      <!-- 评论区域 -->
     <view class="comments-section">
        <view class="section-title">评论 ({{ commentData.length }})</view>
        
        <view class="comment-list">
          <view class="comment-item" v-for="(commentOne, index) in commentData" :key="index">
            <!-- 一级评论 -->
            <image :src="commentOne.avatarUrl" mode="aspectFill" class="comment-avatar"></image>
            <view class="comment-content">
              <view class="comment-header">
                <text class="comment-user">{{ commentOne.nickName }}</text>
                <text class="comment-time">{{ commentOne.time }}</text>
              </view>
              <text class="comment-text">{{ commentOne.content }}</text>
              <view class="comment-actions">
                <text class="action-btn" 
                      :class="{'active': commentLikeStates[commentOne.commentId]}"
                      @tap="likeComment(index)">
                  ❤ {{ commentOne.likeCount }}
                </text>
                <text class="action-btn" @tap="replyComment(index, commentOne.commentId)">💬 回复</text>
              </view>
              
              <!-- 显示/隐藏二级评论按钮（有二级评论才显示） -->
              <view class="subcomment-toggle" @tap="toggleSubComments(commentOne.commentId)" v-if="getSubComments(commentOne.commentId).length > 0">
                <text class="iconfont">{{ isShowSub[commentOne.commentId] ? '↑' : '↓' }}</text>
                <text class="toggle-text">{{ isShowSub[commentOne.commentId] ? '收起回复' : '查看回复(' + getSubComments(commentOne.commentId).length + ')' }}</text>
              </view>
              
              <!-- 二级评论列表（仅当isShowSub为true时显示） -->
              <view class="sub-comment-list" v-if="isShowSub[commentOne.commentId] && getSubComments(commentOne.commentId).length > 0">
                <view class="sub-comment-item" v-for="(subComment, subIndex) in getSubComments(commentOne.commentId)" :key="subIndex">
                  <image :src="subComment.avatarUrl" mode="aspectFill" class="sub-comment-avatar"></image>
                  <view class="sub-comment-content">
                    <view class="sub-comment-header">
                      <!-- 根据是否是回复二级评论显示不同内容 -->
                      <text class="sub-comment-user">
                        {{ subComment.nickName }}
                        <text v-if="subComment.replyTo"> ➜ {{ subComment.replyTo }}</text>
                      </text>
                      <text class="sub-comment-time">{{ subComment.time }}</text>
                    </view>
                    <text class="sub-comment-text">
                      {{ subComment.content }}
                    </text>
                    <view class="sub-comment-actions">
                      <text class="sub-action-btn" 
                            :class="{'active': subCommentLikeStates[`${commentOne.commentId}-${subComment.commentId}`]}"
                            @tap="likeSubComment(commentOne.commentId, subIndex)">
                        ❤ {{ subComment.likeCount }}
                      </text>
                      <text class="sub-action-btn" @tap="replySubComment(index, commentOne.commentId, subComment.commentId, subComment.nickName)">💬 回复</text>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
      
     
    <view class="comment-input-container">
      <input 
        class="comment-input" 
        :placeholder="replyState.replyToName ? '回复 @' + replyState.replyToName : '写评论...'" 
        v-model="newComment"
        @confirm="submitComment"
        @blur="handleInputBlur"
        autofocus
      />
      <button class="submit-btn" @tap="submitComment">发送</button>
    </view>
    </scroll-view>
	<!-- 未登录提示 -->
      <LoginPrompt 
        :is-login="isLogin" 
        prompt-text="请登录后发表评论"
        @goToLogin="goToLogin"
      />
  </view>
</template>

<script setup>
import { ref, onUnmounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import userManager from '../../common/utils/user.js'
import { getPostById, getCommentsByPostId, getCommentsByRootId ,addComment, addFavorite,deleteFavorite,postLike,commentLike } from '../../api/post.js';
import { sendSocketMessage, isSocketConnected } from '../../common/utils/websocket.js'
import { generateSnowflakeId } from '../../common/utils/Snowflake.js'
import TimeUtil from '../../common/utils/time.js'
import LoginPrompt from '../../components/LoginPrompt.vue'

const statusBarHeight = ref(0)
const isLiked = ref(false)
const isFavorited = ref(false)
const newComment = ref('')
const isLogin = ref(false)
const postData = ref({})
const commentData = ref([])
const childComment = ref([])
const isShowSub = ref({}) // 控制二级评论显示/隐藏的状态（默认全部隐藏）
const postId = ref()
// 新增：记录评论点赞状态
const commentLikeStates = ref({}) // 一级评论点赞状态 {commentId: boolean}
const subCommentLikeStates = ref({}) // 二级评论点赞状态 {'rootId-subId': boolean}

// 跟踪当前回复状态
const replyState = ref({
  isReplying: false,       // 是否处于回复状态
  rootId: null,            // 根评论ID（一级评论ID）
  replyToId: null,         // 被回复的评论ID
  replyToName: null        // 被回复的用户名
})

// 获取指定一级评论的二级评论
const getSubComments = (rootId) => {
  return childComment.value.filter(item => item.rootId === rootId)
}

// 切换二级评论显示状态
const toggleSubComments = (commentId) => {
  isShowSub.value[commentId] = !isShowSub.value[commentId]
}

// 打开一级评论输入框
const openMainComment = () => {
  if (!userManager.checkLogin()) {
    showLoginPrompt()
    return
  }
  
  // 设置为一级评论状态
  replyState.value = {
    isReplying: true,
    rootId: null,
    replyToId: null,
    replyToName: null
  }
  newComment.value = '' // 清空输入框
  
  // 滚动到评论区
  uni.createSelectorQuery().select('.comments-section').boundingClientRect(rect => {
    if (rect) {
      uni.pageScrollTo({
        scrollTop: rect.top + (statusBarHeight.value + 88) - 100,
        duration: 300
      })
    }
  }).exec()
}

// 计算九宫格图片高度
const imageHeight = (length) => {
  // 根据图片数量动态调整高度，保持正方形比例
  if (length === 1) {
    return '400rpx' // 单张图片稍大
  } else if (length === 2 || length === 4) {
    return '280rpx' // 2张或4张时调整高度
  }
  return '220rpx' // 其他情况统一高度
}

onLoad(async(options) => {
  postId.value = options.id
  // 获取状态栏高度
  const systemInfo = uni.getSystemInfoSync()
  statusBarHeight.value = systemInfo.statusBarHeight || 0
  
  // 检查登录状态
  checkLoginStatus()
  
  // 监听登录状态变化
  uni.$on('loginStatusChanged', handleLoginStatusChanged)
  
  // 如果有传入的帖子ID，获取帖子详情和评论
  if (options.id) {
    try {
      const userInfo = userManager.getUserInfo()
      const userId = userInfo.userId || ''
      postData.value = await getPostById(options.id, userId)
      console.log('帖子数据:', postData.value)
      
      // 根据返回的isFavorite字段设置初始收藏状态
      isFavorited.value = postData.value.isFavorite === 1
      
      // 获取一级评论
      commentData.value = await getCommentsByPostId(options.id)
      console.log('一级评论:', commentData.value)
      
      // 初始化二级评论显示状态和点赞状态
      commentData.value.forEach(comment => {
        isShowSub.value[comment.commentId] = false
        commentLikeStates.value[comment.commentId] = false // 初始未点赞
      })
      
      // 批量获取所有二级评论
      childComment.value = []
      for (const comment of commentData.value) {
        const subs = await getCommentsByRootId(comment.commentId)
        childComment.value.push(...subs)
        
        // 初始化二级评论点赞状态
        subs.forEach(sub => {
          const key = `${comment.commentId}-${sub.commentId}`
          subCommentLikeStates.value[key] = false // 初始未点赞
        })
      }
      console.log('二级评论:', childComment.value)
    } catch (error) {
      console.error('获取数据失败:', error)
    }
  }
})

onUnmounted(() => {
  uni.$off('loginStatusChanged', handleLoginStatusChanged)
})

const handleLoginStatusChanged = (loginStatus) => {
  isLogin.value = loginStatus
}

const checkLoginStatus = () => {
  isLogin.value = userManager.checkLogin()
}

const goBack = () => {
  uni.navigateBack()
}
// 查看用户资料
	const viewUserProfile = (userId) => {
		if (!userManager.checkLogin()) {
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			})
			setTimeout(() => {
				uni.switchTab({
					url: '/pages/mine/mine'
				})
			}, 1000)
			return
		}
		console.log('View user profile:', userId)
		uni.navigateTo({
			url: `/pages/user-profile/user-profile?userId=${userId}`
		})
	}
const likePost = async () => {
  if (!userManager.checkLogin()) {
    showLoginPrompt()
    return
  }

  // 如果已经点赞，直接返回（不可取消）
  if (isLiked.value) {
    uni.showToast({ title: '已点赞', icon: 'none' })
    return
  }

  // 乐观更新 UI
  postData.value.likeCount++
  isLiked.value = true

  try {
    await postLike(postId.value)
    uni.showToast({ title: '点赞成功', icon: 'success' })
  } catch (error) {
    console.error('帖子点赞操作失败:', error)
    // 失败：回滚 UI（因为不能取消，所以只在失败时回滚）
    isLiked.value = false
    postData.value.likeCount--
    uni.showToast({ title: '点赞失败，请重试', icon: 'none' })
  }
}

// 修改收藏功能，添加接口调用
const favoritePost = async () => {
  if (!userManager.checkLogin()) {
    showLoginPrompt()
    return
  }
  
  const userInfo = userManager.getUserInfo()
  const userId = userInfo.userId || ''
  const favoriteVo = {
    targetId: postId.value,
    userId: userId
  }
  console.log(favoriteVo)
  try {
    if (isFavorited.value) {
      // 取消收藏
      await deleteFavorite(favoriteVo)
      postData.value.favoriteCount--
      isFavorited.value = false
      uni.showToast({
        title: '取消收藏',
        icon: 'success'
      })
    } else {
      // 收藏
      await addFavorite(favoriteVo)
      postData.value.favoriteCount++
      isFavorited.value = true
      uni.showToast({
        title: '收藏成功',
        icon: 'success'
      })
      
      // 发送 WebSocket 通知消息（仅收藏时发送，取消收藏不发送）
      if (isSocketConnected()) {
        // 验证帖子作者ID是否存在且有效（使用userIdStr字符串类型）
        const postAuthorIdStr = postData.value.userIdStr
        if (!postAuthorIdStr || postAuthorIdStr === null || postAuthorIdStr === undefined) {
          console.warn('帖子作者ID不存在，跳过发送收藏通知')
        } else {
          const toIdStr = postAuthorIdStr.toString().trim()
          if (!toIdStr || toIdStr === 'null' || toIdStr === 'undefined') {
            console.warn('帖子作者ID无效，跳过发送收藏通知', postAuthorIdStr)
          } else if (toIdStr === userId.toString()) {
            console.log('自己收藏自己的帖子，跳过发送通知')
          } else {
            try {
              const notificationMsg = {
                id: generateSnowflakeId(),
                toId: toIdStr, // 帖子作者ID（字符串类型）
                fromId: userId.toString(),
                name: '互动消息', // 固定为"互动消息"
                msg: `${userInfo.nickName || userInfo.account || '用户'} 收藏了你的帖子《${postData.value.title}》`,
                headImg: 'https://pet-java-chengdu-123.oss-cn-chengdu.aliyuncs.com/%E7%94%9F%E6%88%90%E5%AE%98%E6%96%B9%E7%8C%AB%E7%8B%97%20logo.png', // 固定头像
                time: TimeUtil.now ? TimeUtil.now() : new Date().toLocaleString(),
                type: "send",
                messageType: "notification"
              }
              console.log('发送收藏通知，toId:', toIdStr, 'fromId:', userId.toString())
              await sendSocketMessage(notificationMsg)
              console.log('收藏通知消息发送成功')
            } catch (wsError) {
              console.error('发送收藏通知消息失败:', wsError)
              // WebSocket 发送失败不影响收藏操作，只记录错误
            }
          }
        }
      }
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
    uni.showToast({
      title: isFavorited.value ? '取消收藏失败' : '收藏失败',
      icon: 'none'
    })
  }
}

// 修改：一级评论点赞/取消点赞
const likeComment = async (index) => {
  if (!userManager.checkLogin()) {
    showLoginPrompt()
    return
  }

  const comment = commentData.value[index]
  const commentId = comment.commentId

  // 如果已点赞，直接返回
  if (commentLikeStates.value[commentId]) {
    uni.showToast({ title: '已点赞', icon: 'none' })
    return
  }

  // 乐观更新
  comment.likeCount++
  commentLikeStates.value[commentId] = true

  try {
    await commentLike(commentId)
    uni.showToast({ title: '点赞成功', icon: 'success' })
  } catch (error) {
    console.error('评论点赞操作失败:', error)
    // 回滚
    commentLikeStates.value[commentId] = false
    comment.likeCount--
    uni.showToast({ title: '点赞失败，请重试', icon: 'none' })
  }
}

// 修改：二级评论点赞/取消点赞（调用 commentLike 接口）
const likeSubComment = async (rootId, subIndex) => {
  if (!userManager.checkLogin()) {
    showLoginPrompt()
    return
  }

  const subComments = getSubComments(rootId)
  const subComment = subComments[subIndex]
  if (!subComment) return

  const key = `${rootId}-${subComment.commentId}`

  // 如果已点赞，直接返回
  if (subCommentLikeStates.value[key]) {
    uni.showToast({ title: '已点赞', icon: 'none' })
    return
  }

  // 乐观更新 UI
  subComment.likeCount++
  subCommentLikeStates.value[key] = true

  try {
    await commentLike(subComment.commentId)
    uni.showToast({ title: '点赞成功', icon: 'success' })
  } catch (error) {
    console.error('二级评论点赞操作失败:', error)
    // 回滚
    subCommentLikeStates.value[key] = false
    subComment.likeCount--
    uni.showToast({ title: '点赞失败，请重试', icon: 'none' })
  }
}

// 回复一级评论
const replyComment = (index, commentId) => {
  if (!userManager.checkLogin()) {
    showLoginPrompt()
    return
  }
  
  const user = commentData.value[index].nickName
  // 更新回复状态并显示输入框
  replyState.value = {
    isReplying: true,
    rootId: commentId,
    replyToId: commentId,
    replyToName: user
  }
  newComment.value = '' // 清空输入框
}

// 回复二级评论
const replySubComment = (parentIndex, rootId, commentId, userName) => {
  if (!userManager.checkLogin()) {
    showLoginPrompt()
    return
  }
  
  // 更新回复状态并显示输入框
  replyState.value = {
    isReplying: true,
    rootId: rootId,
    replyToId: commentId,
    replyToName: userName
  }
  newComment.value = '' // 清空输入框
}


// 修改 handleInputBlur：仅清空内容时不重置状态（因为输入框常驻）
const handleInputBlur = () => {
  // 不再自动关闭 isReplying
  // 如果需要“点击空白取消回复”，可另加逻辑，但题目要求“一直显示”，所以不做处理
}

const submitComment = async () => {
  if (!userManager.checkLogin()) {
    showLoginPrompt()
    return
  }
  
  const content = newComment.value.trim()
  if (!content) {
    uni.showToast({
      title: '请输入评论内容',
      icon: 'none'
    })
    return
  }
  
  const userInfo = userManager.getUserInfo()
  const userId = userInfo.userId || 'anonymous' // 假设用户信息中有userId
  
  // 显示加载中，避免重复提交
  uni.showLoading({ title: '发布中...' })
  
  try {
    // 根据回复状态判断评论类型
    if (!replyState.value.rootId) {
      // 发表一级评论（帖子的直接评论）
      const commentParams = {
        userId: userId,
        postId: postId.value,
        rootId: null,
        parentId: null,
        content: content
      }
      
      // 先调用接口获取真实评论ID
      const commentId = await addComment(commentParams)
      
      // 用真实ID创建评论对象
      const newCommentObj = {
        avatarUrl: userInfo.avatarUrl || '/static/images/user-avatar.png',
        nickName: userInfo.nickName || '用户',
        time: '刚刚',
        content: content,
        likeCount: 0,
        commentId: commentId // 直接使用接口返回的真实ID
      }
      
      // 添加到列表
      commentData.value.unshift(newCommentObj)
      // 初始化新评论的点赞状态
      commentLikeStates.value[commentId] = false
      // 更新帖子评论数
      postData.value.commentCount++
      
      // 发送 WebSocket 通知消息给帖子作者（一级评论）
      if (isSocketConnected()) {
        // 验证帖子作者ID是否存在且有效（使用userIdStr字符串类型）
        const postAuthorIdStr = postData.value.userIdStr
        if (!postAuthorIdStr || postAuthorIdStr === null || postAuthorIdStr === undefined) {
          console.warn('帖子作者ID不存在，跳过发送一级评论通知')
        } else {
          const toIdStr = postAuthorIdStr.toString().trim()
          if (!toIdStr || toIdStr === 'null' || toIdStr === 'undefined') {
            console.warn('帖子作者ID无效，跳过发送一级评论通知', postAuthorIdStr)
          } else if (toIdStr === userId.toString()) {
            console.log('自己评论自己的帖子，跳过发送通知')
          } else {
            try {
              const notificationMsg = {
                id: generateSnowflakeId(),
                toId: toIdStr, // 帖子作者ID（字符串类型）
                fromId: userId.toString(),
                name: '互动消息', // 固定为"互动消息"
                msg: `${userInfo.nickName || userInfo.account || '用户'} 评论了你的帖子《${postData.value.title}》：${content}`,
                headImg: 'https://pet-java-chengdu-123.oss-cn-chengdu.aliyuncs.com/%E7%94%9F%E6%88%90%E5%AE%98%E6%96%B9%E7%8C%AB%E7%8B%97%20logo.png', // 固定头像
                time: TimeUtil.now ? TimeUtil.now() : new Date().toLocaleString(),
                type: "send",
                messageType: "notification"
              }
              console.log('发送一级评论通知，toId:', toIdStr, 'fromId:', userId.toString())
              await sendSocketMessage(notificationMsg)
              console.log('一级评论通知消息发送成功')
            } catch (wsError) {
              console.error('发送一级评论通知消息失败:', wsError)
              // WebSocket 发送失败不影响评论操作，只记录错误
            }
          }
        }
      }
      
    } else {
      // 发表二级评论
      const commentParams = {
        userId: userId,
        postId: postId.value,
        rootId: replyState.value.rootId,
        parentId: replyState.value.replyToId,
        content: content
      }
      
      // 先调用接口获取真实评论ID
      const commentId = await addComment(commentParams)
      
      // 用真实ID创建评论对象
      const newSubComment = {
        avatarUrl: userInfo.avatarUrl || '/static/images/user-avatar.png',
        nickName: userInfo.nickName || '用户',
        time: '刚刚',
        content: content,
        likeCount: 0,
        commentId: commentId,
        rootId: replyState.value.rootId,
        replyTo: replyState.value.isReplying && replyState.value.rootId !== replyState.value.replyToId 
          ? replyState.value.replyToName 
          : null
      }
      
      // 添加到列表
      childComment.value.push(newSubComment)
      // 初始化新二级评论的点赞状态
      const key = `${replyState.value.rootId}-${commentId}`
      subCommentLikeStates.value[key] = false
      
      // 自动展开当前评论的二级评论列表
      isShowSub.value[replyState.value.rootId] = true
      
      // 二级评论也增加帖子总评论数
      postData.value.commentCount++
      
      // 发送 WebSocket 通知消息给被回复的用户（二级评论）
      if (isSocketConnected() && replyState.value.replyToId) {
        try {
          // 查找被回复评论的用户ID
          let replyToUserId = null
          
          // 先在一级评论中查找
          const rootComment = commentData.value.find(c => c.commentId === replyState.value.rootId)
          if (rootComment) {
            // 如果回复的是一级评论，通知一级评论作者
            if (replyState.value.replyToId === replyState.value.rootId) {
              if (rootComment.userId) {
                replyToUserId = rootComment.userId.toString().trim()
              }
            } else {
              // 如果回复的是二级评论，在二级评论列表中查找
              const parentSubComment = childComment.value.find(c => c.commentId === replyState.value.replyToId)
              if (parentSubComment && parentSubComment.userId) {
                replyToUserId = parentSubComment.userId.toString().trim()
              }
            }
          }
          
          // 验证被回复用户ID是否有效
          if (!replyToUserId || replyToUserId === 'null' || replyToUserId === 'undefined') {
            console.warn('无法找到被回复用户的ID，跳过发送二级评论通知', {
              rootId: replyState.value.rootId,
              replyToId: replyState.value.replyToId,
              rootComment: rootComment,
              childComments: childComment.value
            })
          } else if (replyToUserId === userId.toString()) {
            console.log('自己回复自己的评论，跳过发送通知')
          } else {
            const notificationMsg = {
              id: generateSnowflakeId(),
              toId: replyToUserId, // 被回复的用户ID
              fromId: userId.toString(),
              name: '互动消息', // 固定为"互动消息"
              msg: `${userInfo.nickName || userInfo.account || '用户'} 回复了你的评论：${content}`,
              headImg: 'https://pet-java-chengdu-123.oss-cn-chengdu.aliyuncs.com/%E7%94%9F%E6%88%90%E5%AE%98%E6%96%B9%E7%8C%AB%E7%8B%97%20logo.png', // 固定头像
              time: TimeUtil.now ? TimeUtil.now() : new Date().toLocaleString(),
              type: "send",
              messageType: "notification"
            }
            console.log('发送二级评论通知，toId:', replyToUserId, 'fromId:', userId.toString())
            await sendSocketMessage(notificationMsg)
            console.log('二级评论通知消息发送成功')
          }
        } catch (wsError) {
          console.error('发送二级评论通知消息失败:', wsError)
          // WebSocket 发送失败不影响评论操作，只记录错误
        }
      }
    }
    
    // 重置评论框和回复状态
    newComment.value = ''
    replyState.value = {
      isReplying: false,
      rootId: null,
      replyToId: null,
      replyToName: null
    }
    
    uni.showToast({
      title: '评论成功',
      icon: 'success'
    })
  } catch (error) {
    console.error('评论提交失败:', error)
    uni.showToast({
      title: '评论失败，请重试',
      icon: 'none'
    })
  } finally {
    // 隐藏加载中
    uni.hideLoading()
  }
}

const previewImage = (index) => {
  uni.previewImage({
    urls: postData.value.imageUrls || [],
    current: index
  })
}

const showLoginPrompt = () => {
  uni.showToast({
    title: '请先登录',
    icon: 'none'
  })
  setTimeout(() => {
    uni.switchTab({
      url: '/pages/mine/mine'
    })
  }, 1000)
}

const goToLogin = () => {
  uni.switchTab({
    url: '/pages/mine/mine'
  })
}
</script>

<style scoped>
/* 二级评论样式 */
.sub-comment-list {
  margin-left: 40rpx;
  padding-left: 24rpx;
  border-left: 2rpx solid #EEEEEE;
  margin-top: 20rpx;
}

.sub-comment-item {
  display: flex;
  margin-bottom: 20rpx;
}

.sub-comment-avatar {
  width: 56rpx;
  height: 56rpx;
  border-radius: 50%;
  margin-right: 16rpx;
}

.sub-comment-content {
  flex: 1;
  background-color: #F5F5F5;
  border-radius: 16rpx;
  padding: 16rpx;
}

.sub-comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8rpx;
}

.sub-comment-user {
  font-size: 26rpx;
  color: #333333;
}

.sub-comment-time {
  font-size: 22rpx;
  color: #999999;
}

.sub-comment-text {
  font-size: 26rpx;
  color: #555555;
  line-height: 1.5;
  margin-bottom: 8rpx;
}

.sub-comment-actions {
  display: flex;
  gap: 16rpx;
}

.sub-action-btn {
  font-size: 22rpx;
  color: #999999;
}

/* 显示/隐藏回复按钮 */
.subcomment-toggle {
  display: flex;
  align-items: center;
  color: #89CFF0;
  font-size: 24rpx;
  margin: 16rpx 0 0 80rpx;
  cursor: pointer;
}

.toggle-text {
  margin-left: 8rpx;
}

/* 九宫格图片样式 */
.post-images {
  margin: 24rpx 0;
}

.image-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx; /* 图片间距 */
}

.grid-item {
  position: relative;
  border-radius: 16rpx;
  overflow: hidden;
}

.post-image {
  width: 100%;
  height: 100%;
  display: block;
}

/* 超过9张图片时的数量提示 */
.image-count {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
}

/* 原有样式 */
.post-detail-page {
  min-height: 100vh;
  background-color: #F5F5F5;
}

.custom-navbar {
  background: linear-gradient(135deg, #89CFF0 0%, #B7F0AD 100%);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.navbar-content {
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32rpx;
}

.back-btn,
.more-btn {
  width: 64rpx;
  height: 64rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36rpx;
  color: #FFFFFF;
}

.navbar-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #FFFFFF;
}

.content-scroll {
  height: 100vh;
  padding-bottom: 120rpx;
}

.post-content {
  background-color: #FFFFFF;
  margin: 24rpx 32rpx;
  border-radius: 24rpx;
  padding: 32rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
}

.post-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333333;
  margin-bottom: 24rpx;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 32rpx;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 24rpx;
}

.user-detail {
  display: flex;
  flex-direction: column;
}

.username {
  font-size: 32rpx;
  font-weight: 500;
  color: #333333;
  margin-bottom: 8rpx;
}

.post-time {
  font-size: 24rpx;
  color: #999999;
}

.post-body {
  font-size: 30rpx;
  color: #555555;
  line-height: 1.6;
  margin-bottom: 32rpx;
}

.post-actions {
  display: flex;
  justify-content: space-around;
  padding: 24rpx 0;
  border-top: 1rpx solid #EEEEEE;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 32rpx;
  color: #999999;
}

/* 点赞和收藏的激活状态样式 */
.action-item .iconfont.active {
  color: #ff3b30; /* 红色爱心 */
}

.action-item:nth-child(3) .iconfont {
  color: #999999; /* 未收藏时白色星星（实际显示为灰色） */
}

.action-item:nth-child(3) .iconfont.active {
  color: #FFD700; /* 收藏后黄色星星 */
}

.action-text {
  margin-top: 8rpx;
}

.comments-section {
  background-color: #FFFFFF;
  margin: 24rpx 32rpx;
  border-radius: 24rpx;
  padding: 32rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
  margin-bottom: 32rpx;
}

.comment-list {
  padding-bottom: 24rpx;
}

.comment-item {
  display: flex;
  margin-bottom: 32rpx;
}

.comment-avatar {
  width: 64rpx;
  height: 64rpx;
  border-radius: 50%;
  margin-right: 24rpx;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16rpx;
}

.comment-user {
  font-size: 28rpx;
  font-weight: 500;
  color: #333333;
}

.comment-time {
  font-size: 24rpx;
  color: #999999;
}

.comment-text {
  font-size: 28rpx;
  color: #555555;
  line-height: 1.5;
  margin-bottom: 16rpx;
}

.comment-actions {
  display: flex;
  gap: 24rpx;
}

.action-btn {
  font-size: 24rpx;
  color: #999999;
}

/* 点赞激活状态样式 */
.action-btn.active,
.sub-action-btn.active {
  color: #ff3b30; /* 红色爱心 */
}

/* 评论输入框样式 - 默认隐藏，通过replyState.isReplying控制显示 */
.comment-input-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #FFFFFF;
  padding: 24rpx 32rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.08);
  z-index: 999;
}

.comment-input {
  flex: 1;
  height: 72rpx;
  background-color: #F5F5F5;
  border-radius: 36rpx;
  padding: 0 32rpx;
  font-size: 28rpx;
  margin-right: 24rpx;
}

.submit-btn {
  width: 120rpx;
  height: 72rpx;
  background: linear-gradient(135deg, #89CFF0 0%, #B7F0AD 100%);
  border-radius: 36rpx;
  color: #FFFFFF;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>